package dao.Impl;


import dao.ApplyDao;
import entity.Apply;
import handler.CustomBeanApplyListHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import utils.C3p0Helper;

import java.sql.SQLException;
import java.util.List;

public class ApplyDaoImpl implements ApplyDao {


    @Override
    public Apply fingById(int id) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "select * from apply where id=?";
        BeanHandler<Apply> setHandler = new BeanHandler<>(Apply.class);
        try {
            return qr.query(sql,setHandler,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Apply> findAll() {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "select * from apply";
        try {
            return qr.query(sql,new CustomBeanApplyListHandler());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Apply> findByState(int state) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "select * from apply where state = ?";
        try {
            return qr.query(sql,new CustomBeanApplyListHandler(),state);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Apply apply) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "update apply set state=? where id=?";
        try {
            qr.update(sql,apply.getState(),apply.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "delete from apply where id=?";
        try {
            qr.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void add(Apply apply) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "insert into apply(name,email,age,telephone,message,applyTime,state) values(?,?,?,?,?,?,?)";
        try {
            qr.update(sql,apply.getName(),apply.getEmail(),apply.getAge(),apply.getTelephone(),apply.getMessage(),apply.getApplyTime(),apply.getState());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
